import './ComAttr.less'
import { Collapse, App } from 'antd'
const { Panel } = Collapse
import LinkProduct from '../LinkProduct/LinkProduct'
import React, { forwardRef, useImperativeHandle, useRef } from 'react'
import { useEffect, useState } from 'react'
import { useModel } from '@umijs/max'

const ComAttr = ({}, ref) => {
  const bannerLinkProductRef = useRef()
  const navigationLinkProductRef = useRef()
  const { message } = App.useApp()
  const { AddShopDecoration, currentTab, currentSelectCom, setCurrentSelectCom } = useModel('ShopDecoration')
  const [activeKey, setActiveKey] = useState([])

  const comList = [
    {
      key: 'navigationArr',
      label: '导航',
      children: () => {
        return (
          <>
            <TipText type='navigationArr' />
            <LinkProduct type='navigationArr' ref={navigationLinkProductRef} />
          </>
        )
      }
    },
    {
      key: 'bannerArr',
      label: 'Banner',
      children: () => {
        return (
          <>
            <TipText type='bannerArr' />
            <LinkProduct type='bannerArr' ref={bannerLinkProductRef} />
          </>
        )
      }
    }
  ]

  const TipText = ({ type }) => {
    let obj = {
      bannerArr: '建议图片尺寸: 高度 330 像素,宽度 1060 像素',
      navigationArr: '建议图片为正方向'
    }

    return (
      <div className='com_tip_text'>
        <p className='com_tip_title'>添加图片</p>
        <p className='com_tip_content'>{obj[type]}</p>
      </div>
    )
  }

  // 处理表单提交
  const handleFinish = async () => {
    const bannerValues = bannerLinkProductRef?.current && (await bannerLinkProductRef?.current?.handleFinish())
    const navigationValues =
      navigationLinkProductRef?.current && (await navigationLinkProductRef?.current?.handleFinish())
    // 最终获取到的提交的数据
    const params = { ...bannerValues, ...navigationValues, plt: currentTab?.label }
    // console.log('params========', params)
    const res = await AddShopDecoration(params)
    if (res) {
      // console.log('res========', res)
      message.success('发布成功')
    }
  }

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    handleFinish
  }))

  const handleCollapseChange = key => {
    setActiveKey(key)
    setCurrentSelectCom(key?.[0] || key)
  }

  useEffect(() => {
    setActiveKey(currentSelectCom)
  }, [currentSelectCom])

  return (
    <div className='com_attr'>
      <Collapse activeKey={activeKey} bordered={false} onChange={handleCollapseChange}>
        {comList.map(item => {
          return (
            <Panel header={item.label} key={item.key}>
              {item.children()}
            </Panel>
          )
        })}
      </Collapse>
    </div>
  )
}

export default forwardRef(ComAttr)
